package com.df.bpm.utils.businessViewer;

import com.df.bpm.dto.BusinessEntityDTO;
import com.df.bpm.entity.BusinessEntity;
import com.df.bpm.entity.EntityType;
import com.df.bpm.utils.businessViewer.entityDialogServices.EntityDTOservice;
import com.df.bpm.utils.businessViewer.stepsTableServices.EntityService;
import com.df.common.utils.CommonUtils;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class EntityDialog {

    int unit=10;
    JDialog jd=new JDialog();
    JPanel jp=new JPanel();

    List<JTextField> fields;
    Font iFont;
    Integer selectResultID;

    EntityDTOservice entityDTOservice;
    EntityService entityService;


    public EntityDialog(EntityService entityService) {
        this.entityService=entityService;
        entityDTOservice=new EntityDTOservice();
        unit= (int) MainPanel.unit;
        iFont=new Font("宋体", Font.PLAIN, (int) (MainPanel.unit));
        jd.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                // 关闭窗口时触发
            }
        });
        jd.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        jd.setSize(40*unit, 30*unit);
    }

    public Integer selectEntity(BusinessEntity oldEntity) {
        if(CommonUtils.varIsBlank(oldEntity)){
            selectResultID=null;
        }else{
            selectResultID=oldEntity.getBusinessEntityIndex();
        }
        repaint4selectDialog();
        return selectResultID;
    }

    private void repaint4selectDialog() {
        jd.remove(jp);
        jd.setLocationRelativeTo(null);
        jd.setLayout(null);
        jp=new JPanel();
        jp.setLayout(null);
        jp.setSize(jd.getSize());

        fields=new ArrayList<>();
        addFields4SelectDialog(fields,"名称");
        addFields4SelectDialog(fields,"类型");
        addFields4SelectDialog(fields,"担当的业务");
        addFields4SelectDialog(fields,"当作输入的业务");
        addFields4SelectDialog(fields,"当作输出的业务");

        JTextField lastField=fields.get(fields.size()-1);
        JScrollPane scr=new JScrollPane();
        scr.setLocation(unit,lastField.getY()+lastField.getHeight()+unit);
        scr.setSize(jp.getWidth()-3*unit, jp.getHeight()-4*unit-scr.getY());
        jp.add(scr);


        for(JTextField field:fields){
            field.addKeyListener(
                    new KeyAdapter(){
                        public void keyPressed(KeyEvent e)
                        {
                            if(e.getKeyChar()==KeyEvent.VK_ENTER )   //按回车键执行相应操作;
                            {
                                search4SelectDialog(fields,scr);
                            }
                        }
                    });
        }

        jd.add(jp);
        jd.setModal(true);
        jd.repaint();
        jd.setVisible(true);

    }

    private void search4SelectDialog(List<JTextField> fields, JScrollPane scr) {
        BusinessEntityDTO temp=new BusinessEntityDTO();
        if (CommonUtils.varIsNotBlank(fields.get(0).getText())) {
            temp.setName(fields.get(0).getText());
        }
        if (CommonUtils.varIsNotBlank(fields.get(1).getText())) {
            temp.setTypeName(fields.get(1).getText());
        }
        if (CommonUtils.varIsNotBlank(fields.get(2).getText())) {
            temp.setMasterBusiness(fields.get(2).getText());
        }
        if (CommonUtils.varIsNotBlank(fields.get(3).getText())) {
            temp.setInput2Business(fields.get(3).getText());
        }
        if (CommonUtils.varIsNotBlank(fields.get(4).getText())) {
            temp.setOutput4Business(fields.get(4).getText());
        }
        List<BusinessEntityDTO> list = entityDTOservice.getList4Like(temp);
        showBusinessEntityDTOlist4SelectDialog(scr,list);
    }

    private void showBusinessEntityDTOlist4SelectDialog(JScrollPane scr, List<BusinessEntityDTO> list) {
        scr.getViewport().removeAll();
        String[] title = {"ID","序号", "名称", "类型", "担当的业务", "当作输入的业务", "当作输出的业务"};
        DefaultTableModel model = new DefaultTableModel(null, title){
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return false;//不允许编辑，留作触发双击或拖拽
            }
        };
        if(CommonUtils.varIsNotBlank(list)) {
            for (int n=0;n<list.size();n++) {
                BusinessEntityDTO row=list.get(n);
                model.addRow(new Object[]{row.getBusinessEntityIndex(),list.size()-n, row.getName(), row.getTypeName(),
                        row.getMasterBusiness(),row.getInput2Business(),row.getOutput4Business()});
            }
        }
        model.addRow(new Object[]{null,null, null, null, null, null, null});
        list.add(new BusinessEntityDTO());
        JTable iTable=EntityTypeDialog.newTable4SelectDialog(model, iFont);
        iTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        iTable.getColumnModel().getColumn(1).setPreferredWidth(2*unit);
        iTable.getColumnModel().getColumn(2).setPreferredWidth(10*unit);
        iTable.getColumnModel().getColumn(3).setPreferredWidth(3*unit);
        iTable.getColumnModel().getColumn(4).setPreferredWidth(15*unit);
        iTable.getColumnModel().getColumn(5).setPreferredWidth(15*unit);
        iTable.getColumnModel().getColumn(6).setPreferredWidth(15*unit);
        Main.hideCol(iTable,0);
        scr.getViewport().add(iTable);
        iTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int row = iTable.rowAtPoint(e.getPoint());
                int col = iTable.columnAtPoint(e.getPoint());
                if (row >= 0 ) {
                    if (e.getClickCount() == 2) {// 处理双击事件
                        System.out.println("Row " + row + "& Col "+col+" double clicked");
                        String entityID=""+iTable.getValueAt(row, 0);
                        if(col==1 && CommonUtils.varIsNotBlank(entityID)){//不为空的双击代表选中
                            selectResultID=list.get(row).getBusinessEntityIndex();
                            jd.dispose();//选好窗口消失
                        }else{// 双击空行触发新增 BusinessEntity
                            Integer result=null;
                            if(col==2){
                                result=editEntityDesc(iTable,row,list);
                            }else if(col==3){
                                result=editEntityType(iTable,row,list);
                            }
                            if(result!=null && result>0){
                                search4SelectDialog(fields,scr);
                            }
                        }

                    }
                }
            }
        });

    }

    private Integer editEntityDesc(JTable iTable, int row, List<BusinessEntityDTO> list) {
        Integer result=null;
        String oldValue=""+iTable.getValueAt(row, 2);
        String tips="请输入主体描述：";
        String newValue= (String) JOptionPane.showInputDialog(null, tips, "主体描述", JOptionPane.PLAIN_MESSAGE, null, null, oldValue);
        if(newValue!=null && !newValue.isEmpty() && !oldValue.equals(newValue)){
            iTable.setValueAt(newValue,row,2);
            Integer entityID=list.get(row).getBusinessEntityIndex();
            if(CommonUtils.varIsBlank(entityID)){
                entityID=null;
            }
            Integer typeID=list.get(row).getEntityTypeIndex();
            if(CommonUtils.varIsBlank(typeID)){
                typeID=null;
            }
            BusinessEntity temp=new BusinessEntity()
                    .setBusinessEntityIndex(entityID)
                    .setName(newValue)
                    .setEntityTypeIndex(typeID);
            result=updateBusinessEntity(temp);
            list.get(row).setName(newValue);
        }
        return result;
    }

    private Integer editEntityType(JTable iTable, int row, List<BusinessEntityDTO> list) {
        Integer result=null;
        Integer oldTypeID=list.get(row).getEntityTypeIndex();
        EntityType newType=selectEntityType(oldTypeID);
        if(oldTypeID==null || !Objects.equals(newType.getEntityTypeIndex(), oldTypeID)){
            iTable.setValueAt(newType.getName(),row,3);
            BusinessEntityDTO dto=list.get(row);
            Integer entityID=dto.getBusinessEntityIndex();
            if(CommonUtils.varIsBlank(entityID)){
                entityID=null;
            }
            String entityName=dto.getName();
            if(CommonUtils.varIsBlank(entityName)){
                entityName=null;
            }
            BusinessEntity temp=new BusinessEntity()
                    .setBusinessEntityIndex(entityID)
                    .setName(entityName)
                    .setEntityTypeIndex(newType.getEntityTypeIndex());
            result=updateBusinessEntity(temp);
            list.get(row).setEntityTypeIndex(newType.getEntityTypeIndex());
            list.get(row).setTypeName(newType.getName());
        }
        return result;
    }

    private EntityType selectEntityType(Integer oldTypeID) {// 弹窗选择主体类型
        return new EntityTypeDialog().selectEntityType(oldTypeID);
    }

    private Integer updateBusinessEntity(BusinessEntity temp) {
        return entityService.updateEntity(temp);
    }


    private void addFields4SelectDialog(List<JTextField> fields, String colName) {
        EntityTypeDialog.addFields4SelectDialog(fields, colName, unit, iFont, jp);
    }

}
